/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package it.tukano.text;

import it.tukano.collections.LinkedListExt;
import it.tukano.collections.ListExt;
import it.tukano.fun.Tuple2;

/**
 * Finds tokens in a string
 * @author utente3
 */
public class StringScanner {
    private final String start, end;

    /**
     * Initializes this StringScanner
     * @param start the sequence of chars that starts a token
     * @param end the sequence of chars that ends a token
     */
    public StringScanner(String start, String end) {
        this.start = start;
        this.end = end;
    }

    /**
     * Finds all the tokens in the given text. Uses the tokens passed during
     * construction as start/end markers. The matches are returned as start-end
     * indices, relative to the text sequence of chars. The start-end indices
     * includes the start-end tokens length.
     * @param text the text to scan
     * @return a list of start-end indices, one for each token match.
     */
    public ListExt<Tuple2<Integer, Integer>> find(String text) {
        ListExt<Tuple2<Integer, Integer>> tokens = new LinkedListExt<Tuple2<Integer, Integer>>();
        for(int i = 0; i < text.length(); i++) {
            int s = text.indexOf(start, i);
            if(s < 0) break;
            int e = text.indexOf(end, s + start.length());
            if(e < 0) break;

            i = e + end.length();
            tokens.add(Tuple2.newInstance(s, e + end.length()));
        }
        return tokens;
    }
    
    public static int backIndexOf(String text, String token, int index) {
        StringBuilder buffer = new StringBuilder();
        for(int i = index; i >= 0; i--) {
            buffer.insert(0, text.charAt(i));
            if(buffer.indexOf(token) == 0) return i;
        }
        return -1;
    }
}
